package com.booklove.controller.book;


import com.booklove.constant.JudgeStateConstant;
import com.booklove.context.BaseContext;
import com.booklove.domain.dto.PageDTO;
import com.booklove.domain.dto.WishbookDTO;
import com.booklove.domain.po.Address;
import com.booklove.domain.po.Books;
import com.booklove.domain.po.Wishbook;
import com.booklove.domain.query.WishbookQuery;
import com.booklove.domain.vo.WishbookVO;
import com.booklove.exception.AddressSubmitException;
import com.booklove.exception.DonateBookCreateException;
import com.booklove.exception.DonateBookDeleteException;
import com.booklove.result.Result;
import com.booklove.service.delivery.AddressService;
import com.booklove.service.book.BooksService;
import com.booklove.service.book.WishbookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController("wishbookCLL")
@RequestMapping("/wishbooks")
@RequiredArgsConstructor// 使用基本注解的注入形式，仅仅注入需要的变量
public class WishbookController {

    private final WishbookService wishbookService;

    private final BooksService booksService;

    private final AddressService addressService;

    /**
     * 保存新增一本许愿书籍，
     * 自动提交审核
     */
    @PostMapping("/")
    @Transactional
    public Result<String> saveWishbook(@RequestBody WishbookDTO wishbookDTO) {
        // 验证信息非空
        /*
        验证：
        - 许愿title
        - 许愿内容content
        - 许愿书籍名称bookName
        - 存在封面
         */
        if (wishbookDTO.getTitle() == null || wishbookDTO.getTitle().isBlank()
                || wishbookDTO.getBookName() == null || wishbookDTO.getBookName().isBlank()
                || wishbookDTO.getContent() == null || wishbookDTO.getContent().isBlank()
                || wishbookDTO.getPicture() == null || wishbookDTO.getPicture().isBlank()
        ) {
            throw new DonateBookCreateException("书籍信息或是捐献信息缺失");
        }

        Integer addressId = wishbookDTO.getAddressId();
        Address address = addressService.getById(addressId);
        if (address == null || address.getUserId() != BaseContext.getCurrentId().intValue()) {
            throw new AddressSubmitException("地址信息非法，请检测内容");
        }


        // 查询对应的书本信息
        Books book = wishbookDTO.buildBookEntity();

        booksService.save(book);
        Integer bookId = book.getId();
        // 存入wish
        Wishbook wishbook = Wishbook.createWishBook(wishbookDTO);

        // 添加回填的bookId
        wishbook.setBookId(bookId);

        // 保存许愿
        wishbookService.save(wishbook);


        // 生成对应的审核单号



        return Result.success();
    }


    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/id")
    Result<String> deleteWishbook(@RequestParam("id") Long id) {
        Wishbook wishbook = wishbookService.getById(id);
        if (wishbook == null) {
            throw new DonateBookDeleteException("非法的捐书删除请求");
        }
        if (wishbook.getUserId() != BaseContext.getCurrentId().intValue()) {
            throw new DonateBookDeleteException("非法的捐书删除请求");
        }


        Integer bookId = wishbook.getBookId();
        // 删除对应的书本
        booksService.removeById(bookId);
        wishbookService.removeById(id);
        return Result.success();
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    WishbookVO getWishbook(@PathVariable Integer id) {
        WishbookVO wishbookVO = wishbookService.getVOById(id);
        return wishbookVO;
    }


    /**
     * 编辑数据
     *
     * @param wishbookDTO 实体
     * @return 编辑结果
     */
    @PutMapping("/")
    Result<String> updateWishbook(@RequestBody WishbookDTO wishbookDTO) {
        // 存入wish
        Wishbook wishbook = wishbookService.getById(wishbookDTO.getId());
        // 如果dto中有null字段，那么也会被覆盖，然后在update方法中，不会被执行更新
        BeanUtils.copyProperties(wishbookDTO, wishbook);
        // 添加回填的bookId
        Integer bookId = wishbook.getBookId();
        wishbookService.updateById(wishbook);


        // 查询对应的书本信息
        Books book = wishbookDTO.buildBookEntity();
        //写入bookId
        book.setId(bookId);
        booksService.updateById(book);


        return Result.success();
    }


    /**
     * 分页查询
     *
     * @param wishbookQuery 筛选条件
     * @return 查询结果
     */
    @GetMapping("/page")
    PageDTO<WishbookVO> wishbooksPageQuery(WishbookQuery wishbookQuery) {
        return wishbookService.queryWishbooksPage(wishbookQuery);
    }


    /**
     * 分页查询
     *
     * @param wishbookQuery 筛选条件
     * @return 查询结果
     */
    @GetMapping("/list")
    PageDTO<WishbookVO> wishbooksListQuery(WishbookQuery wishbookQuery) {
        // 强制为获取审核通过的
        wishbookQuery.setJudgeState(JudgeStateConstant.ACCEPT);
        return wishbookService.queryWishbooksPage(wishbookQuery);
    }
}

